#include "ticksheetwindow.h"

#include "../recordedtime.h"
#include "../ticksheet.h"

#include "ui_ticksheetwindow.h"

#include <QDateTime>
#include <QTime>
#include <QTimer>
#include <QMessageBox>
#include <QTreeView>
#include <QStandardItemModel>
#include <QFileDialog>
#include <QTextStream>
#include <QCompleter>
#include <QByteArray>
#include <QFile>
#include <QTextStream>
#include <QHeaderView>
#include <QModelIndex>

TicksheetWindow::TicksheetWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::TicksheetWindow),
    mCurrentTicksheet(0)
{
    ui->setupUi(this);

    //
    // Timer panel
    //

    ui->clockTimeLabel->setText(QString("00:00.00"));
    ui->startButton->setEnabled(true);
    ui->restartButton->setEnabled(false);
    ui->startedLabel->setText("Timer not started");
    //ui->startTimeLabel->setText(mElapsedTime->toString());
    ui->recordButton->setEnabled(false);
    ui->noteEdit->setEnabled(false);

    mRecordedTimesModel = new QStandardItemModel();
    QStringList headerLabels;
    headerLabels << "#" << "Elapsed time" << "Notes";
    mRecordedTimesModel->setHorizontalHeaderLabels(headerLabels);

    mTreeView = ui->treeView;
    mTreeView->setAlternatingRowColors(true);
    mTreeView->setRootIsDecorated(false);
    mTreeView->setModel(mRecordedTimesModel);
    mTreeView->setColumnWidth(0, 25);
    mTreeView->header()->setResizeMode(QHeaderView::ResizeToContents);

    ui->actionRecord->setEnabled(false);

    makeDir();
}

TicksheetWindow::~TicksheetWindow()
{
    delete ui;
}

void TicksheetWindow::makeDir()
{
    QString dateString = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    mRootDir = QDir::homePath();

    QString subDir;
    QTextStream(&subDir) << "Racetime/" << dateString;

    mRootDir.mkpath(subDir);
    mRootDir.cd(subDir);

    qDebug("Made working directory at '%s'", qPrintable( mRootDir.absolutePath() ));
}

void TicksheetWindow::on_startButton_clicked()
{
    if (mCurrentTicksheet)
        delete mCurrentTicksheet;

    // Start a new timer session
    mCurrentTicksheet = new Ticksheet(0,ui->syncHours->value(),
                                        ui->syncMins->value(),
                                        ui->syncSecs->value());

    ui->startedLabel->setText("Clock start time:");
    ui->startTimeLabel->setText(mCurrentTicksheet->elapsedTimeString());

    ui->startButton->setEnabled(false);
    ui->restartButton->setEnabled(true);

    ui->recordButton->setEnabled(true);
    ui->noteEdit->setEnabled(true);

    ui->clockTimeLabel->setStyleSheet("background-color: rgba(207, 255, 203, 150);");
    ui->numberLabel->setText("1");
    ui->noteEdit->setFocus();
    ui->actionRecord->setEnabled(true);

    connect(mCurrentTicksheet, SIGNAL(timeChanged(const QString&)),
            SLOT(on_timerChanged(const QString&)));
    connect(mCurrentTicksheet, SIGNAL(timeRecorded()),
            SLOT(slot_buildResultslist()));
}

void TicksheetWindow::on_restartButton_clicked()
{
    int ret = QMessageBox::warning(this, tr("RaceTime"),
                                    tr("This will reset the race time to 00:00.00!\n"
                                    "Are you sure you want to do this?"),
                                    QMessageBox::Cancel | QMessageBox::Yes);
    if (ret == QMessageBox::Yes)
    {
        on_actionQuickSave_triggered();

        mCurrentTicksheet->stop();

        //mElapsedTime->restart();

        ui->startButton->setEnabled(true);
        ui->restartButton->setEnabled(false);
        ui->clockTimeLabel->setStyleSheet("");

        ui->startedLabel->setText("Timer reset");
        ui->startTimeLabel->setText("");

        ui->recordButton->setEnabled(false);
        ui->noteEdit->setEnabled(false);
        ui->actionRecord->setEnabled(false);
    }
}

void TicksheetWindow::on_recordButton_clicked()
{
    const QString note = ui->noteEdit->text();
    RecordedTime* recordedTime = mCurrentTicksheet->recordTime(note);

    //Update our timer list by inserting the new item
    QList<QStandardItem*> standardItemList = recordedTime->standardItemList();
    mRecordedTimesModel->appendRow(standardItemList);

    //Scroll down so we always see the new item
    mTreeView->scrollToBottom();

    //Reset the note line edit for the next entry
    ui->noteEdit->setText("");
    ui->noteEdit->setFocus();

    //Update the record number field
    ui->numberLabel->setText(QString().setNum(mRecordedTimesModel->rowCount()));
}

void TicksheetWindow::on_timerChanged(const QString& elapsed )
{
    ui->clockTimeLabel->setText(elapsed);
}

void TicksheetWindow::on_noteEdit_returnPressed()
{
    on_recordButton_clicked();
}

void TicksheetWindow::on_noteEdit_textChanged ( const QString & text )
{
    QString uppertext = text.toUpper();
    ui->noteEdit->setText(uppertext);
}

void TicksheetWindow::on_actionSave_triggered()
{
    QString dateTimeString = QDateTime::currentDateTime().toString("hh-mm-ss-zzz");
    QString timerFile;
    QTextStream(&timerFile) << "timer-" << dateTimeString << ".txt";
    QString suggestedFileName = mRootDir.absoluteFilePath(timerFile);

    QString fileName = QFileDialog::getSaveFileName(this,
                                                    "Save a tab delimited file of tick times",
                                                    suggestedFileName);
    if (fileName.isEmpty())
        return;
    mCurrentTicksheet->saveFile(fileName);
}

void TicksheetWindow::on_actionQuickSave_triggered()
{
    QString dateTimeString = QDateTime::currentDateTime().toString("hh-mm-ss-zzz");
    QString timerFile;
    QTextStream(&timerFile) << "quick-timer-" << dateTimeString << ".txt";
    QString fileName = mRootDir.absoluteFilePath(timerFile);

    qDebug("Writing timer file: '%s'", qPrintable(fileName));

    mCurrentTicksheet->saveFile(fileName);
}

void TicksheetWindow::on_actionToggleWarning_triggered()
{
    mCurrentTicksheet->toggleLastTimeWarning();
}

void TicksheetWindow::on_actionRecord_triggered()
{
    on_recordButton_clicked();
}

